package com.library.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.library.Mapper.UserMapper;
import com.library.commen.context.BaseContext;
import com.library.pojo.PageResult;
import com.library.pojo.User;
import com.library.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;


@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    /**
     * 添加用户
     * @param user
     */
    @Override
    public void add(User user) {
        user.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));;
        userMapper.add(user);
    }

    /**
     * 根据分页查询
     * @param page
     * @param pageSize
     * @param name
     * @param status
     * @return
     */
    @Override
    public PageResult pageQuery(Integer page, Integer pageSize,
                                String name, Integer status) {
        PageHelper.startPage(page,pageSize);
        Page<User> p = userMapper.list(name,status);
        return new PageResult(p.getTotal(),p.getResult());
    }

    /**
     * 启用禁用用户
     * @param status
     */
    @Override
    public void startOrStop(Integer status,Long id) {
        userMapper.startOrStop(status,id);
    }
    /**
     * 根据id查询用户
     */
    @Override
    public User getById(Long id) {
        User user = userMapper.getById(id);
        return user;
    }

    /**
     * 修改用户
     * @param user
     */
    @Override
    public void update(User user) {
        user.setUpdateTime(LocalDateTime.now());
        userMapper.update(user);
    }

    /**
     * 用户查看自己的信息
     * @return
     */
    @Override
    public User getUserId() {
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);
        return user;
    }

    /**
     * 用户注册
     * @param user
     */
    @Override
    public void register(User user) {
        String password = user.getPassword();
        user.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));;
        userMapper.add(user);
    }
}
